// API测试模块，方便添加新的测试项目
import axios from 'axios';

// API基础URL
const API_BASE_URL = 'http://localhost:3000';

/**
 * API测试模块集合
 * 每个模块包含一组相关的测试
 */
export const testModules = {
  // 模块1： 基础待办事项模块
  basicTodos: {
    name: "基础待办事项操作",
    description: "测试基本的待办事项创建、读取、更新和删除功能",
    tests: [
      {
        name: "GET /todos 获取所有待办事项",
        run: async () => {
          try {
            const response = await axios.get(`${API_BASE_URL}/todos`);
            
            if (!Array.isArray(response.data)) {
              throw new Error('响应不是数组格式');
            }
            
            return {
              passed: true,
              response: {
                status: response.status,
                data: response.data
              },
              message: `成功获取 ${response.data.length} 个待办事项`
            };
          } catch (error) {
            return {
              passed: false,
              error: error.message,
              response: error.response ? {
                status: error.response.status,
                data: error.response.data
              } : {}
            };
          }
        }
      },
      {
        name: "POST /todos 创建待办事项",
        run: async () => {
          try {
            const newTodo = {
              title: `测试待办事项 ${Date.now()}`,
              completed: true
            };
            
            const response = await axios.post(`${API_BASE_URL}/todos`, newTodo);
            
            if (!response.data || !response.data.id || response.data.title !== newTodo.title) {
              throw new Error('创建的待办事项缺少必要字段或数据不匹配');
            }
            
            // 保存新创建的ID供其他测试使用
            testContext.lastCreatedTodoId = response.data.id;
            
            return {
              passed: true,
              response: {
                status: response.status,
                data: response.data
              },
              message: `成功创建待办事项: ${response.data.title}`
            };
          } catch (error) {
            return {
              passed: false,
              error: error.message,
              response: error.response ? {
                status: error.response.status,
                data: error.response.data
              } : {}
            };
          }
        }
      }
    ]
  },
  
  // 模块2： 待办事项过滤模块
  todoFilters: {
    name: "待办事项过滤和查询",
    description: "测试待办事项的过滤和查询功能",
    active: true,
    tests: [
      {
        name: "GET /todos?completed=true 过滤已完成待办事项",
        run: async () => {
          try {
            // 首先创建一个已完成的待办事项
            const completedTodo = {
              title: `已完成待办事项 ${Date.now()}`,
              completed: true
            };
            
            await axios.post(`${API_BASE_URL}/todos`, completedTodo);
            
            // 测试过滤
            const response = await axios.get(`${API_BASE_URL}/todos?completed=true`);
            
            if (!Array.isArray(response.data)) {
              throw new Error('响应不是数组格式');
            }
            
            if (response.data.length === 0) {
              throw new Error('没有找到已完成的待办事项');
            }
            
            if (!response.data.every(todo => !!todo.completed)) {
              console.log(response.data);
              throw new Error('存在未完成的待办事项在结果中');
            }
            
            response.message = `成功过滤 ${response.data.length} 个已完成待办事项`;
            return {
              passed: true,
              response: {
                status: response.status,
                data: response.data
              },
            };
          } catch (error) {
            return {
              passed: false,
              error: error.message,
              response: error.response ? {
                status: error.response.status,
                data: error.response.data
              } : {}
            };
          }
        }
      },
      {
        name: "GET /todos?completed=false 过滤未完成待办事项",
        run: async () => {
          try {
              // 首先创建一个未完成的待办事项
              const incompleteTodo = {
                title: `未完成待办事项 ${Date.now()}`,
                completed: false
              };
              
              await axios.post(`${API_BASE_URL}/todos`, incompleteTodo);
              
              // 测试过滤
              const response = await axios.get(`${API_BASE_URL}/todos?completed=false`);
              
              if (!Array.isArray(response.data)) {
                throw new Error('响应不是数组格式');
              }
              
              if (response.data.length === 0) {
                throw new Error('没有找到未完成的待办事项');
              }
              
              if (!response.data.every(todo => !todo.completed )) {
                throw new Error('存在已完成的待办事项在结果中');
              }
              
              response.message = `成功过滤 ${response.data.length} 个未完成待办事项`;
              return {
                passed: true,
                response: {
                  status: response.status,
                  data: response.data
                },
              }
            } catch (error) {
              return {
                passed: false,
                error: error.message,
                response: error.response ? {
                  status: error.response.status,
                  data: error.response.data
                } : {}
              };
            }
        }
      },
      {
        name: "PATCH /todos/:id 更新待办事项完成状态",
        run: async () => {
          try {
              // 创建一个新的待办事项
              const createResponse = await axios.post(`${API_BASE_URL}/todos`, {
                title: `待更新的待办事项 ${Date.now()}`,
                completed: false
              });
              
              const todoId = createResponse.data.id;
              
              // 更新待办事项的完成状态
              const updateResponse = await axios.patch(`${API_BASE_URL}/todos/${todoId}`, {
                completed: true
              });
              
              // 验证响应
              if (!updateResponse.data || updateResponse.data.id !== todoId || !updateResponse.data.completed) {
                throw new Error('更新待办事项完成状态失败');
              }
              
              updateResponse.message = `成功更新待办事项完成状态，ID: ${todoId}`;
              return {
                passed: true,
                response: {
                  status: updateResponse.status,
                  data: updateResponse.data
                },
              };
            } catch (error) {
              return {
                passed: false,
                error: error.message,
                response: error.response ? {
                  status: error.response.status,
                  data: error.response.data
                } : {}
              };
            }
        }
      },
    ]
  },

  // 模块3: AI建议API测试
  aiSuggestions: {
    name: "AI建议API测试",
    description: "测试AI驱动的待办事项建议功能",
    active: true,
    tests: [
      {
        name: "POST /suggest 获取任务建议",
        run: async () => {
          try {
              const suggestionRequest = {
                task: `下周三到周五运动会，今天是 ${Date.now()}，请调整现有计划任务`
              };
              
              const response = await axios.post(`${API_BASE_URL}/suggest`, suggestionRequest, {
                timeout: 60000  // AI API响应较慢，超时时间60秒
              });
              
              // 验证响应
              if (!response.data || !response.data.task || !response.data.suggestion) {
                throw new Error('AI建议响应缺少必要字段');
              }
              
              response.message = `成功获取AI建议: ${response.data.suggestion.substring(0, 200)}...`;
              return {
                passed: true,
                response: {
                  status: response.status,
                  data: response.data
                },
              };
            } catch (error) {
              return {
                passed: false,
                error: error.message,
                response: error.response ? {
                  status: error.response.status,
                  data: error.response.data
                } : {}
              };
            }
        }
      }
    ]
  },
  
  // 要添加新的测试模块，只需在这里添加一个新的对象
  // 例如:
  /*
  newFeature: {
    name: "新功能测试",
    description: "测试新添加的功能",
    tests: [
      {
        name: "测试名称",
        run: async () => {
          try {
            // 测试实现...
            return {
                  passed: true,
                  response: {
                    status: response.status,
                    data: response.data
                  },
                };
              }
            } catch (error) {
              return {
                passed: false,
                error: error.message,
                response: error.response ? {
                  status: error.response.status,
                  data: error.response.data
                } : {}
              };
            }
        }
      }
    ]
  }
  */
};

// 测试上下文，用于在测试之间共享数据
export const testContext = {
  lastCreatedTodoId: null
};

/**
 * 运行所有API测试
 * @returns {Object} 测试结果
 */
export async function runAllTests() {
  console.log('开始执行API测试...');
  
  // 初始化结果
  const results = {
    totalPassed: 0,
    totalFailed: 0,
    tests: []
  };
  
  // 重置测试上下文
  Object.assign(testContext, {
    lastCreatedTodoId: null
  });
  
  // 运行所有模块的测试
  for (const [moduleId, module] of Object.entries(testModules)) {
    console.log(`\n测试模块: ${module.name}`);
    console.log(module.description);
    
    // 运行模块中的每个测试
    for (const test of module.tests) {
      console.log(`\n运行测试: ${test.name}`);
      
      try {
        // 执行测试
        const testResult = await test.run();
        
        if (testResult.passed) {
          results.totalPassed++;
          console.log(`✅ 通过: ${testResult.message || "测试通过"}`);
        } else {
          results.totalFailed++;
          console.log(`❌ 失败: ${testResult.error || "测试失败"}`);
        }
        
        // 记录测试结果
        results.tests.push({
          name: test.name,
          passed: testResult.passed,
          response: testResult.response || {},
          error: testResult.passed ? null : testResult.error,
          score: {
            value: testResult.passed ? 10 : 0,
            maxValue: 10,
            comments: testResult.passed ? (testResult.message || "通过测试") : testResult.error
          }
        });
      } catch (error) {
        // 测试执行出错
        results.totalFailed++;
        results.tests.push({
          name: test.name,
          passed: false,
          error: `测试执行出错: ${error.message}`,
          score: {
            value: 0,
            maxValue: 10,
            comments: `测试执行出错: ${error.message}`
          }
        });
        console.log(`❌ 错误: ${error.message}`);
      }
    }
  }
  
  // 计算得分和总结信息
  results.score = Math.floor((results.totalPassed / (results.totalPassed + results.totalFailed || 1)) * 100) || 0;
  results.maxPossibleScore = (results.totalPassed + results.totalFailed) * 10;
  results.timestamp = new Date().toISOString();
  
  console.log(`\n测试完成: ${results.totalPassed}/${results.totalPassed + results.totalFailed} 通过 (${results.score}%)`);
  
  return results;
}

/**
 * 从API获取待办事项
 * @returns {Promise<Array>} 待办事项数组
 */
export async function fetchTodos() {
  try {
    console.log('从API获取待办事项...');
    const response = await axios.get(`${API_BASE_URL}/todos`, { timeout: 3000 });
    
    if (Array.isArray(response.data)) {
      console.log(`成功获取 ${response.data.length} 个待办事项`);
      return response.data;
    } else {
      console.warn('API返回了非数组数据');
      return [];
    }
  } catch (error) {
    console.warn('获取待办事项失败:', error.message);
    return [];
  }
}

export default {
  runAllTests,
  fetchTodos,
  testModules,
  testContext
};